package com.yuexiao.controller;

import com.yuexiao.entity.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @ClassName:GlobalExceptionHandler
 * @Auther: YUEXIAO
 * @Description: 全局异常处理
 * @Date: 2022/8/11 14:04
 * @Version: v1.0
 */
@ControllerAdvice(annotations = {RestController.class,Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /*
        异常处理方法
     */
    @ExceptionHandler(Exception.class)
    public ResultInfo exceptionInfo(Exception ex){
        log.error("拦截错误,{},结束",ex.getMessage());
        if(ex.getMessage().contains("DuplicateKeyException")){
            int start = ex.getMessage().indexOf("Duplicate entry")+"Duplicate entry".length();
            int end = ex.getMessage().indexOf("for key");
            String msg = ex.getMessage().substring(start,end) + "已存在";
            return ResultInfo.error(msg);
        }
        if(ex.getMessage().contains("不允许访问")){
            return ResultInfo.error("无权限访问或操作");
        }
        if(ex.getMessage().contains("have association")){
            return ResultInfo.error("当前分类下关联了菜品，不能删除");
        }
        if(ex.getMessage().contains("系统找不到指定的文件")){
            return ResultInfo.error("未加载到资源文件");
        }
        if(ex.getMessage().contains("该菜品有关联套餐")){
            return ResultInfo.error("菜品中有关联的套餐，请先从套餐中取消勾选");
        }
        return ResultInfo.error("未知错误");
    }

}
